<!-- 高德地图-组件 -->
<template>
  <div class="amap-container">
    <div class="search-box">
      <input v-model="searchKey" type="search" id="search" />
      <el-button @click="searchByHand" size="mini" type="primary"
        >搜索</el-button
      >
      <el-button @click="submitAddress" size="mini" type="success"
        >确认</el-button
      >
      <div class="tip-box" id="searchTip"></div>
    </div>

    <el-amap
      class="amap-box"
      :amap-manager="amapManager"
      :vid="'amap-vue'"
      :zoom="zoom"
      :plugin="plugin"
      :center="center"
      :events="events"
    >
      <el-amap-marker
        v-for="(marker, index) in markers"
        :position="marker"
        :key="index"
      >
      </el-amap-marker>
    </el-amap>
  </div>
</template>

<script>
import Vue from 'vue'
import AMap from 'vue-amap'
Vue.use(AMap)
import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap";

let amapManager = new AMapManager();

export default {
  name: "MyAmap",
  data() {
    const that = this;
    console.log('加载了地图1.4.4版本吗？');

    // 初始化地图
    AMap.initAMapApiLoader({
      // 高德的key（js端）
      key: '533e81b8ae97b2caae38b47e7fb001d9',
      // 插件集合
      plugin: [
        'AMap.Autocomplete', 
        'AMap.PlaceSearch', 
        'AMap.Scale', 
        'AMap.OverView', 
        'AMap.ToolBar', 
        'AMap.MapType', 
        'AMap.PolyEditor', 
        'AMap.CircleEditor',
        'AMap.Geolocation', 
        'AMap.Geocoder', 
        'AMap.AMapManager', 
        'AMap.Marker'
      ],
      v: '1.4.4',       // 版本
      uiVersion: '1.0' // ui版本
    });

    return {
      address: null,
      searchKey: "",
      amapManager,
      markers: [],
      searchOption: {
        city: "全国",
        citylimit: true,
      },
      emitData: {
        lng: 0,
        lat: 0,
        address: "",
      },
      center: [121.329402, 31.228667],
      zoom: 17,
      lng: 0,
      lat: 0,
      loaded: false,
      markerEvent: {
        click(e) {},
      },
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            that.initSearch();
          });
        },
        // 点击获取地址的数据
        // lng精度
        // lat维度
        click(e) {
          that.markers = [];
          let { lng, lat } = e.lnglat;
          that.lng = lng;
          that.lat = lat;

          that.center = [lng, lat];
          that.markers.push([lng, lat]);
          // 这里通过高德 SDK 完成。
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all",
          });
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                that.address = result.regeocode.formattedAddress;
                that.searchKey = result.regeocode.formattedAddress;
                that.$nextTick();
              }
            }
          });
        },
      },
      // 一些工具插件
      plugin: [
        {
          // 定位
          pName: "Geolocation",
          events: {
            init(o) {
              // o是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  // 设置经度
                  that.lng = result.position.lng;
                  // 设置维度
                  that.lat = result.position.lat;
                  // 设置坐标
                  that.center = [that.lng, that.lat];
                  that.markers.push([that.lng, that.lat]);
                  // load
                  that.loaded = true;
                  // 页面渲染好后
                  that.$nextTick();
                }
              });
            },
            click(e) {},
          },
        },
        {
          // 工具栏
          pName: "ToolBar",
          events: {
            init(instance) {},
          },
        },
        {
          // 鹰眼
          pName: "OverView",
          events: {
            init(instance) {},
          },
        },
        {
          // 地图类型
          pName: "MapType",
          defaultType: 0,
          events: {
            init(instance) {},
          },
        },
        {
          // 搜索
          pName: "PlaceSearch",
          events: {
            init(instance) {},
          },
        },
      ],
    };
  },
  methods: {
    submitAddress() {
      this.$emit("getAmapData", this.emitData);
    },
    initSearch() {
      let vm = this;
      let map = this.amapManager.getMap();
      AMapUI.loadUI(["misc/PoiPicker"], function (PoiPicker) {
        var poiPicker = new PoiPicker({
          input: "search",
          placeSearchOptions: {
            map: map,
            pageSize: 10,
          },
          suggestContainer: "searchTip",
          searchResultsContainer: "searchTip",
        });
        vm.poiPicker = poiPicker;
        // 监听poi选中信息
        poiPicker.on("poiPicked", function (poiResult) {
          let source = poiResult.source;
          let poi = poiResult.item;
          if (source !== "search") {
            poiPicker.searchByKeyword(poi.name);
          } else {
            poiPicker.clearSearchResults();
            vm.markers = [];
            let lng = poi.location.lng;
            let lat = poi.location.lat;
            let address = poi.cityname + poi.adname + poi.name;
            vm.center = [lng, lat];
            vm.markers.push([lng, lat]);
            vm.lng = lng;
            vm.lat = lat;
            vm.address = address;
            vm.searchKey = address;
            vm.emitData = {
              lng,
              lat,
              address: vm.searchKey,
            };
          }
        });
      });
    },
    searchByHand() {
      if (this.searchKey !== "") {
        this.poiPicker.searchByKeyword(this.searchKey);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.amap-container {
  width: 100%;
  height: 60vh;
  position: relative;
  border: 1px solid #999;
  margin-bottom: 8px;

  .search-box {
    position: absolute;
    z-index: 5;
    width: 70%;
    left: 13%;
    top: 10px;
    height: 30px;

    input {
      float: left;
      width: 59%;
      height: 100%;
      font-size: 13px;
      border: 2px solid #30ccc1;
      padding: 0 8px;
      outline: none;
    }

    button {
      float: left;
      margin-left: 5px;
      /* width: 20%;
            height: 100%;
            background: #30ccc1;
            border: 1px solid #30ccc1;
            color: #fff;
            outline: none; */
    }
  }

  .tip-box {
    width: 100%;
    max-height: 260px;
    position: absolute;
    top: 30px;
    overflow-y: auto;
    background-color: #fff;
  }
}
</style>